﻿using UnityEngine;
using System.Collections;

public class FadeObject : MonoBehaviour {

    public float startAlpha;
    public float endAlpha = 0.0f;
    public float Duration;
    public float delay;
    public bool loop;
    private float alpha2;

	// Use this for initialization
	void Start () 
    {
        transform.renderer.material.color = new Color(transform.renderer.material.color.r, transform.renderer.material.color.g, transform.renderer.material.color.b, startAlpha);
        StartCoroutine(FadeTo());
        
	}
	
	// Update is called once per frame
	void Update () 
    {
        alpha2 = transform.renderer.material.color.a;
	}

    IEnumerator FadeTo()
    {
       float alpha = transform.renderer.material.color.a;
       yield return new WaitForSeconds(delay);
            
            for (float t = 0.0f; t < 1.0f; t += Time.deltaTime / Duration)
            {
                Color newColor = new Color(transform.renderer.material.color.r, transform.renderer.material.color.g, transform.renderer.material.color.b, Mathf.Lerp(alpha, endAlpha, t));
                transform.renderer.material.color = newColor;
                yield return null;
            }
        //System.Array.Reverse(transforms);
        if (endAlpha == 1)
        {
            endAlpha = 0;
        }
        else
        {
            endAlpha = 1;
        }
        if (loop)
        {
            StartCoroutine(FadeTo());
        }
    }
}
